/**
 * 
 */
package com.ermax.aircond.common.dao;

import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.stereotype.Repository;

import com.ermax.aircond.common.dao.WriteMachineDataDao;
import com.ermax.aircond.common.domain.WriteMachineData;
import com.ermax.aircond.report.domain.CommandCheck;
import com.ermax.aircond.util.dao.AbstractHibernateDao;

/**
 * @author Eric
 *
 */
@Repository("writeMachineDataDao")
public class WriteMachineDataDao extends AbstractHibernateDao<WriteMachineData> {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 1418603846702420259L;

	private static final Logger logger = Logger.getLogger(WriteMachineDataDao.class);
	
	public WriteMachineDataDao() {
		setClazz(WriteMachineData.class);
	}
	
	/* (non-Javadoc)
	 * @see com.ermax.aircond.common.dao.WriteMachineDataDao#create(com.ermax.aircond.common.domain.WriteMachineData)
	 */
	public void insert(WriteMachineData writeMachineData) {
		this.create(writeMachineData);
	}

	public List<WriteMachineData> listData() {
		
		return this.findAll();
		
	}

	public WriteMachineData select(short nid) {
		
		Criteria criteria = getCurrentSession().createCriteria(WriteMachineData.class);
		if(isNotNull(nid)){
			criteria.add(Restrictions.eq("nid", nid));
		}
		
		List<WriteMachineData> results = criteria.list();
		if(results.size() > 0){
			return results.get(0);
		}
		
		return null;	
		
	}
	
	@Override
	public void update(WriteMachineData writeMachineData) {
		logger.debug("Write Machine Data: " + writeMachineData);
		
		super.update(writeMachineData);	
		
		/*
    	try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			logger.error(e.getLocalizedMessage());
		}
		
		Query q = this.getCurrentSession().createSQLQuery("Update dbo.MData set dbo.MData.cmd=0 from dbo.MData m inner join dbo.SData s on m.nid = s.nid where s.rcmd=1 and m.nid = :nid");
		q.setParameter("nid", writeMachineData.getNid());
		
		q.executeUpdate();
		 * 
		 */
	}
	
	public void setCommand(WriteMachineData writeMachineData) {
		logger.debug("Set Command Data: " + writeMachineData.getCmd());
		super.update(writeMachineData);	
		
	}

	public void updateStatus() {
		
		logger.debug("Schedule Update Machine Data!");
		
		Query q = this.getCurrentSession().createSQLQuery("Update dbo.MData set dbo.MData.cmd=0 from dbo.MData m inner join dbo.SData s on m.nid = s.nid where s.rcmd=1");
		//q.setParameter("nid", writeMachineData.getNid());
		
		q.executeUpdate();
	}

	@SuppressWarnings("unchecked")
	public List<CommandCheck> findLatestMachineData() {
		
		String strSQL = "select nid, rev, setCmd, cmdTime, currentCmd from ( select ma.nid, ma.rev, ma.cmd as setCmd, dateadd(hh, 8, DATEADD(ss, ar.timestamp/(1000), '1/1/1970')) cmdTime, s.data as currentCmd ,case when (substring (s.data, charindex('C', s.data)+1, 2) NOT LIKE '%[^0-9]%' and substring (ma.cmd, charindex('D', ma.cmd)+1, 2) NOT LIKE '%[^0-9]%' and ma.cmd <> 'E3' and s.data <> 'E3') then case when (abs(convert(int, substring (ma.cmd, charindex('D', ma.cmd)+1, 2)) - convert(int, substring (s.data, charindex('C', s.data)+1, 2))) > 1) then 'true' end when (s.data = 'E3' or substring (s.data, charindex('C', s.data)+1, 2) NOT LIKE '%[^0-9]%' or substring (ma.cmd, charindex('D', ma.cmd)+1, 2) NOT LIKE '%[^0-9]%') then 'true' else 'false' end as chk from dbo.MData_AUD ma, dbo.AUD_REVISION ar, dbo.SData s, (select nid, max(rev) rev from dbo.MData_AUD group by nid) as ma2 where ma.nid = ma2.nid and ma.rev = ma2.rev and ma.nid = s.nid and ma.REV = ar.id and datediff(hh, dateadd(hh, 8, DATEADD(ss, ar.timestamp/(1000), '1/1/1970')), sysdatetime()) > 2 ) as temp where chk = 'true'";
		
		Query query = this.getCurrentSession().createSQLQuery(strSQL).setResultTransformer(Transformers.aliasToBean(CommandCheck.class));
		 
		List<CommandCheck> list = query.list();

		return list;
	}
}
